package com.pray.praymall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.pray.common.utils.R;
import com.pray.praymall.cart.feign.ProductFeignService;
import com.pray.praymall.cart.interceptor.CartInterceptor;
import com.pray.praymall.cart.service.CartService;
import com.pray.praymall.cart.vo.CartItemVo;
import com.pray.praymall.cart.vo.CartVo;
import com.pray.praymall.cart.vo.SkuInfoVo;
import com.pray.praymall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * do something
 *
 * @author 魂悸魄
 * @date 2020/9/23 22:02
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor pool;

    private static final String CART_PREFIX = "praymall:cart:";

    @Override
    public void addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        CartItemVo cartItemVo;
        if (StringUtils.isEmpty(res)) {
            // 购物车无此商品
            // 添加新商品到购物车
            cartItemVo = new CartItemVo();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                // 1、远程查询当前要添加的商品信息
                R r = productFeignService.getSkuInfo(skuId);
                if (r.getCode() == 0) {
                    SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                    });
                    // 2、商品添加到购物车
                    cartItemVo.setCheck(true);
                    cartItemVo.setCount(num);
                    cartItemVo.setSkuId(skuId);
                    cartItemVo.setTitle(skuInfo.getSkuTitle());
                    cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                    cartItemVo.setPrice(skuInfo.getPrice());
                }
            }, pool);

            // 3、远程查询sku的组合信息
            CompletableFuture<Void> getAttrTask = CompletableFuture.runAsync(() -> {
                List<String> attrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVo.setSkuAttr(attrValues);
            }, pool);

            CompletableFuture.allOf(getSkuInfoTask, getAttrTask).get();
        } else {
            // 购物车有此商品
            cartItemVo = JSON.parseObject(res, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
        }
        // 存入redis中
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItemVo));
    }

    @Override
    public CartItemVo getCartItem(Long skuId) {
        return JSON.parseObject((String) getCartOps().get(skuId.toString()), CartItemVo.class);
    }

    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        CartVo cartVo = new CartVo();
        List<CartItemVo> cartItems;
        String cartKey;
        if (userInfoTo.getUserId() != null) {
            // 登录用户
            cartKey = CART_PREFIX + userInfoTo.getUserId();
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            // 如果临时购物车的数据还没有进行合并
            List<CartItemVo> tempItems = getCartItems(tempCartKey);
            if (tempItems != null) {
                // 临时购物车有数据，需要进行合并
                for (CartItemVo item : tempItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
                // 合并完后需要清除临时购物车
                clearCart(tempCartKey);
            }
        } else {
            // 临时用户
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        cartItems = getCartItems(cartKey);
        cartVo.setItems(cartItems);
        return cartVo;
    }

    @Override
    public void clearCart(String key) {
        redisTemplate.delete(key);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItemVo item = getCartItem(skuId);
        item.setCheck(check == 1);
        getCartOps().put(skuId.toString(), JSON.toJSONString(item));
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItemVo item = getCartItem(skuId);
        item.setCount(num);
        getCartOps().put(skuId.toString(), JSON.toJSONString(item));
    }

    @Override
    public void deleteItem(Long skuId) {
        getCartOps().delete(skuId.toString());
    }

    @Override
    public List<CartItemVo> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        } else {
            List<CartItemVo> cartItems = getCartItems(CART_PREFIX + userInfoTo.getUserId());
            List<CartItemVo> collect = cartItems.stream()
                    .filter(CartItemVo::getCheck)
                    .peek(item -> {
                        R r = productFeignService.getPrice(item.getSkuId());
                        if (r.getCode() == 0) {
                            // 更新为新价格
                            item.setPrice(new BigDecimal((String) r.get("data")));
                        }

                    })
                    .collect(Collectors.toList());
            return collect;
        }
    }

    /**
     * 获取购物车的redis操作类
     *
     * @return 购物车的redis操作类
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey;
        if (userInfoTo.getUserId() != null) {
            // 登录用户
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        return redisTemplate.boundHashOps(cartKey);
    }

    /**
     * 获取指定购物车的所有购物项
     *
     * @param key 购物车的key
     * @return 所有购物项
     */
    private List<CartItemVo> getCartItems(String key) {
        BoundHashOperations<String, Object, Object> cartOps = redisTemplate.boundHashOps(key);
        List<Object> values = cartOps.values();
        if (values != null && values.size() > 0) {
            List<CartItemVo> collect = values.stream().map(item -> {
                String str = (String) item;
                return JSON.parseObject(str, CartItemVo.class);
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

}
